package com.laiyima.zhongjiang.linghuilv.demo.me;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;

import com.laiyima.zhongjiang.linghuilv.demo.R;
import com.laiyima.zhongjiang.linghuilv.demo.util.BottomDialog;
import com.laiyima.zhongjiang.linghuilv.demo.util.CircleImageView;
import com.laiyima.zhongjiang.linghuilv.demo.util.CropImageUtils;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.PermissionListener;

import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.File;
import java.util.List;

import me.imid.swipebacklayout.lib.app.SwipeBackActivity;

public class SettingActivity extends SwipeBackActivity implements View.OnClickListener, BottomDialog.OnBottomMenuItemClickListener {
    private LinearLayout imageView;
    private TextView textView;
    private Button button;
    private EditText linearLayout;

    private CircleImageView head_image;
    private BottomDialog bottomDialog;
    private String TAG = "SettingActivity";
    private int settingCode;

    private SettingActivity mContext;

    public static final int REQUEST_CODE_PERMISSION_STORAGE = 100;
    //相机
    private static final int REQUEST_EXTERNAL_STORAGE = 1;
    public static final int REQUEST_CODE_PERMISSION_CAMERA = 101;

    private static String[] PERMISSIONS_STORAGE = {
            "android.permission.READ_EXTERNAL_STORAGE",
            "android.permission.WRITE_EXTERNAL_STORAGE",
            "android.permission.CAMERA"
    };


    public static void verifyStoragePermissions(Activity activity) {

        try {
            //检测是否有写的权限
            int permission = ActivityCompat.checkSelfPermission(activity,
                    "android.permission.WRITE_EXTERNAL_STORAGE");
            if (permission != PackageManager.PERMISSION_GRANTED) {
                // 没有写的权限，去申请写的权限，会弹出对话框
                ActivityCompat.requestPermissions(activity, PERMISSIONS_STORAGE, REQUEST_EXTERNAL_STORAGE);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    protected boolean useThemestatusBarColor = false;//是否使用特殊的标题栏背景颜色，android5.0以上可以设置状态栏背景色，如果不使用则使用透明色值

    protected void setStatusBar() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {//5.0及以上
            View decorView = getWindow().getDecorView();
            int option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
            decorView.setSystemUiVisibility(option);
            //根据上面设置是否对状态栏单独设置颜色
            if (useThemestatusBarColor) {
                // getWindow().setStatusBarColor(getResources().getColor(R.color.colorTheme));
            } else {
                getWindow().setStatusBarColor(Color.TRANSPARENT);
            }
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {//4.4到5.0
            WindowManager.LayoutParams localLayoutParams = getWindow().getAttributes();
            localLayoutParams.flags = (WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS | localLayoutParams.flags);
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {//android6.0以后可以对状态栏文字颜色和图标进行修改
            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_setting);
        imageView = (LinearLayout) findViewById(R.id.setting_back);
        textView = (TextView) findViewById(R.id.setting_number);
        button = (Button) findViewById(R.id.exit_button);
        linearLayout = (EditText) findViewById(R.id.modif_linearyout);
        head_image = (CircleImageView) findViewById(R.id.setting_head_image);
        setStatusBar();
        mContext = this;

        imageView.setOnClickListener(this);
         button.setOnClickListener(this);
        head_image.setOnClickListener(this);

        SharedPreferences sharedPreferences = getSharedPreferences("userinfo.txt", Context.MODE_PRIVATE);
        String mobile = sharedPreferences.getString("mobile", "");
        textView.setText(mobile);

        verifyStoragePermissions(this);

        bottomDialog = new BottomDialog(this, R.layout.dialog_bottom_layout, new int[]{R.id.pick_photo_album, R.id.pick_photo_camera, R.id.pick_photo_cancel});
        bottomDialog.setOnBottomMenuItemClickListener(this);
        showIcon();
    }

    private void showIcon() {
        //String icon_path = SpUtil.getString(mContext, GlobalVariables.USER_ICON_FILE_PATH);
        SharedPreferences sharedPreferences = getSharedPreferences("userinfo.txt", Context.MODE_PRIVATE);
        String icon_path = sharedPreferences.getString("headimagepath", "");
        Log.e(TAG, "icon_path        " + icon_path);
        if (icon_path != null && isFileExist(icon_path)) {
            Bitmap bitmap = BitmapFactory.decodeFile(icon_path);
            head_image.setImageBitmap(bitmap);
        }
    }

    public static boolean isFileExist(String icon_path) {
        File file = new File(icon_path);
        if (file.exists()) {
            return true;
        }
        return false;
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        switch (id) {
            case R.id.setting_back:
                finish();
                break;
            case R.id.exit_button:
                String name=linearLayout.getText().toString();
                exitUser(name);
                break;
            case R.id.setting_head_image:
                bottomDialog.show();
                break;
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        CropImageUtils.getInstance().onActivityResult(mContext, requestCode, resultCode, data, new CropImageUtils.OnResultListener() {
            @Override
            public void takePhotoFinish(String path) {
                //拍照回调，去裁剪
                CropImageUtils.getInstance().cropPicture(mContext, path);
            }

            @Override
            public void selectPictureFinish(String path) {
                //相册回调，去裁剪
                CropImageUtils.getInstance().cropPicture(mContext, path);
            }

            @Override
            public void cropPictureFinish(String path) {
                //   LogUtils.d("path", path + " .....");
                //TODO 上传图片
                SharedPreferences sharedPreferences = getSharedPreferences("userinfo.txt", Context.MODE_PRIVATE); //私有数据
                SharedPreferences.Editor editor = sharedPreferences.edit();
                editor.putString("headimagepath", path);
                editor.commit();
                //                upload(path);
                showIcon();
            }

        });

    }


    private void exitUser(String name) {

        SharedPreferences sharedPreferences = getSharedPreferences("userinfo.txt", Context.MODE_PRIVATE);
        String userID = sharedPreferences.getString("userID", "");
        RequestParams params1 = new RequestParams("http://zljl.laiima.com/index.php?s=/lfl_api/Commonlfl/edit_name");
        //需要带入的参数
        params1.addBodyParameter("uid", userID);
        params1.addBodyParameter("name", name);
        // params.addBodyParameter("captcha", captcha);
        x.http().post(params1, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {

                Log.e(TAG, "回调成功");
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    settingCode = jsonObject.optInt("code", 0);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (settingCode == 200) {
                    Toast.makeText(getApplicationContext(),"修改成功",Toast.LENGTH_SHORT).show();
                    finish();
                }
                if (settingCode == 201) {
                    Toast.makeText(getApplicationContext(),"昵称输入不能为空",Toast.LENGTH_SHORT).show();

                }
                if (settingCode == 202) {
                    Toast.makeText(getApplicationContext(),"该昵称已被使用",Toast.LENGTH_SHORT).show();
                }
                if (settingCode == 205) {
                    Toast.makeText(getApplicationContext(),"修改失败",Toast.LENGTH_SHORT).show();
                }

                if (settingCode == 500) {

                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Log.e(TAG, "查看实名认证失败");
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    @Override
    public void onBottomMenuItemClick(BottomDialog dialog, View view) {
        switch (view.getId()) {
            case R.id.pick_photo_album: //从相册选
//                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
//                    checkPermission(REQUEST_CODE_PERMISSION_STORAGE);
//                } else {
//                    CropImageUtils.getInstance().openAlbum(this);
//                }

                CropImageUtils.getInstance().openAlbum(this);
                break;
            case R.id.pick_photo_camera: //拍照
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    checkPermission(REQUEST_CODE_PERMISSION_CAMERA);
                } else {
                    CropImageUtils.getInstance().takePhoto(this);
                }
                break;

        }
    }

    public void checkPermission(int permissionType) {
        if (Build.VERSION.SDK_INT >= 23) {
            switch (permissionType) {
                //调用单个权限
                case REQUEST_CODE_PERMISSION_STORAGE:
                    if (!AndPermission.hasPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)) {
                        AndPermission.with(this)
                                .requestCode(REQUEST_CODE_PERMISSION_STORAGE)
                                .permission(Manifest.permission.READ_EXTERNAL_STORAGE)
                                .callback(permissionListener)
                                .start();
                    } else {
                        // CropImageUtils.getInstance().openAlbum(mContext);

                    }
                    break;
                //调用多个权限，相机和存储(拍照)
                case REQUEST_CODE_PERMISSION_CAMERA:
                    //如果没有申请权限
                    if (!AndPermission.hasPermission(this, Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                        AndPermission.with(this)
                                .requestCode(REQUEST_CODE_PERMISSION_CAMERA)
                                .permission(Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE)
                                .callback(permissionListener)
                                .start();
                    } else {
                        CropImageUtils.getInstance().takePhoto(mContext);
                    }
                    break;
            }
        }
    }

    private PermissionListener permissionListener = new PermissionListener() {
        @Override
        public void onSucceed(int requestCode, @NonNull List<String> grantPermissions) {
            switch (requestCode) {
                case REQUEST_CODE_PERMISSION_STORAGE: {
                    CropImageUtils.getInstance().openAlbum(mContext);
                    break;
                }
                case REQUEST_CODE_PERMISSION_CAMERA: {
                    CropImageUtils.getInstance().takePhoto(mContext);
                    break;
                }
            }
        }

        @Override
        public void onFailed(int requestCode, @NonNull List<String> deniedPermissions) {
            switch (requestCode) {
                case REQUEST_CODE_PERMISSION_STORAGE: {
                    Toast.makeText(SettingActivity.this, "获取读取sd卡权限失败", Toast.LENGTH_SHORT).show();
                    break;
                }
                case REQUEST_CODE_PERMISSION_CAMERA: {
                    Toast.makeText(SettingActivity.this, "获取拍照权限失败", Toast.LENGTH_SHORT).show();
                    break;
                }
            }
        }
    };
}
